import datetime
import requests
import bs4
import json
import time
import os


def open_url(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
    }
    res = requests.get(url, headers=headers)
    return res


def getNowDayURL(URL):
    NowMonth = datetime.datetime.now().month
    NowDay = datetime.datetime.now().day
    print("正在请求废钢行情列表")
    res = open_url(URL)
    print("正在解析废钢行情列表")
    soup = bs4.BeautifulSoup(res.text, "html.parser")
    AlldateInfo = soup.find_all("p")
    for item in AlldateInfo:
        try:
            if str(NowMonth) + "月" + str(NowDay) + "日国内废钢行情汇总" in item.a.get_text():
                return item.a['href']
        except Exception:
            continue
    return ""


def getURLinfo(URL):
    print("正在请求废钢行情信息")
    res = open_url(URL)
    print("正在解析废钢行情列表")
    soup = bs4.BeautifulSoup(res.text, "html.parser")
    AlldateInfo = soup.find_all("tr")
    # data = ""
    data = "| 城市 | 规格 | 今日价格 | 比昨天 | 比上周 | 备注 |"
    data = data + "\n| ---- | -------- |  ------ |  ----- |  ----- |  ------- |  "
    Price = []
    for item in AlldateInfo:
        td = item.find_all("td")
        if td[0].get_text() == "城市" and td[1].get_text() == "规格":
            continue
        try:
            data = data + f"  \n| {td[0].get_text()} | {td[1].get_text()} | {td[2].get_text()} | {td[3].get_text()} | {td[4].get_text()} | {td[5].get_text()}"
            # data = data + "\n"
            # data = data + " 城市：" + td[0].get_text()
            # data = data + " 规格：" + td[1].get_text()
            # data = data + " 今日价格：" + td[2].get_text()
            # data = data + " 比昨天：" + td[3].get_text()
            # data = data + " 比上周：" + td[4].get_text()
            # data = data + " 备注：" + td[5].get_text()
            if not td[5].get_text() in "当地市场不含税价":
                if len(Price) < 20:
                    Price.append(int(td[5].get_text().split("不含税")[1]))
        except Exception:
            continue
    data = data + f"\n\n不含税总价格：{sum(Price)}，数量：{len(Price)}"
    data = data + f"\n\n平均不含税价格：{(sum(Price) / len(Price)) * 0.9}"
    return data


def sendMessage(title, message):
    url = "https://sc.ftqq.com/SCU95883T9d3eccc99f6b4ef72e93f1fc8bc698735ea82df776916.send"
    params = {
        'text': str(title),
        'desp': str(message)
    }
    try:
        res = requests.post(url, data=params)
    except Exception:
        return False
    if json.loads(res.text)["errmsg"] == "success":
        return True
    else:
        print("错误：" + json.loads(res.text)["errmsg"])
        return False


def main():
    ConfigFile = os.path.dirname(__file__) + os.path.basename(__file__).split(".")[0] + ".ini"
    if not os.path.exists(ConfigFile):
        with open(ConfigFile, "w", encoding="utf8") as f:
            f.write("")
    while True:
        NowDate = datetime.datetime.now().date()
        try:
            f = open(ConfigFile, "r", encoding="utf8")
            if str(NowDate) in f.read():
                print("检测到今日已推送信息，两小时后继续")
                time.sleep(3600 * 2)
                continue
        except Exception:
            pass
        URL = getNowDayURL("http://www.96369.net/news/list/19/19/1")
        if URL == "":
            print("未获取到今日行情，十分钟后继续")
            time.sleep(600)
            continue
        URL = "http://www.96369.net" + str(URL)
        print("正在获取今日废钢行情：" + URL)
        data = getURLinfo(URL)
        print("正在推送信息")
        if not sendMessage("今日废钢行情 - " + str(NowDate), data):
            print("信息推送失败，十分钟后继续")
            time.sleep(600)
            continue
        print("信息推送成功")
        try:
            f = open(ConfigFile, "r+", encoding="utf8")
            f.write(f.read() + "\n" + str(NowDate))
            f.close()
        except Exception:
            print("文件保存失败，正在采取尝试修复")
            if not os.path.exists(ConfigFile):
                with open(ConfigFile, "w", encoding="utf8") as f:
                    f.write(str(NowDate))


if __name__ == '__main__':
    main()
